<template>
  <el-dialog v-model="dialogFormVisible" title="添加菜品" width="880">
    <el-card>
      <template #header>
        <el-input
          v-model="dishName"
          style="width: 240px"
          placeholder="请输入菜品名称进行搜索"
          size="small"
          clearable
          :prefix-icon="Search"
          @click="goSearch"
        />
      </template>
      <div class="addDishCon">
        <!-- 左侧菜品分类的导航菜单 -->
        <el-row>
          <el-col :span="4">
            <el-scrollbar height="320">
              <el-menu default-active="1">
                <el-menu-item
                  :index="idx"
                  v-for="(item, idx) in dishCategoryList"
                  :key="item.id"
                  @click="handleGetCategoryDishes(item.id)"
                  scrollbar-always-on="true"
                >
                  <span>{{ item.name }}</span>
                </el-menu-item>
              </el-menu>
            </el-scrollbar>
          </el-col>
          <el-col :span="10">
            <div class="dish-candidate">
              <!-- 候选菜品 -->
              <el-table
                ref="dishListTableRef"
                :data="dishInCategoryList"
                style="width: 100%"
                :height="320"
                empty-text="本分类下无菜品"
                :row-key="getRowKey"
                @select="onSelectOneDish"
                @select-all="onSelectAllDish"
              >
                <el-table-column
                  type="selection"
                  width="55"
                  :reserve-selection="true"
                />
                <el-table-column label="菜品" width="120" property="name">
                </el-table-column>
                <el-table-column property="price" label="价格"
                  ><template #default="scope">
                    <strong>&yen;&nbsp;{{ scope.row.price / 100 }} </strong>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="10">
            <!-- 已选菜品 -->
            <div class="dish-checked" style="height: 320px">
              <div class="checked-title">
                已选菜品({{ dishCheckedList.length }})
              </div>
              <el-scrollbar height="320">
                <div class="checked-items">
                  <div
                    v-for="(item, idx) in dishCheckedList"
                    :key="idx"
                    class="item"
                  >
                    <span class="dish-name">{{ item.name }}</span>
                    <span class="price"
                      >￥ {{ Number(item.price) / 100 }}
                    </span>
                    <span class="del" @click="removeDish(item.id)">
                      <img src="@/assets/icons/btn_delete@2x.png" />
                    </span>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <div>
      <!-- <AddDish ref="adddish" :check-list="checkList" :seach-key="seachKey" @checkList="getCheckList" /> -->
    </div>
    <template #footer>
      <el-button @click="onDishAddCancel">取 消</el-button>
      <el-button type="primary" @click="onDishAddSuccess">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineOptions } from 'vue'
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { reqGetCategoryListNoPage } from '@/api/category'
import { reqDishListNoPage } from '@/api/dish'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'DishSelect'
})

const open = () => {
  dialogFormVisible.value = true
  //清空已选菜品
  dishCheckedList.value = []
  //清空勾选(全不选)
  dishListTableRef.value.clearSelection()
}
defineExpose({
  open
})

const dialogFormVisible = ref(false)
const dishListTableRef = ref(null)
//检索
const seachKey = ref('')
//搜索的菜品名称
const dishName = ref('')

//菜品已选列表
const dishCheckedList = ref([])

//菜品的分类列表(仅菜品分类，不含套餐分类)
const dishCategoryList = ref([])
const getDishCategoryList = async () => {
  const res = await reqGetCategoryListNoPage({ type: 1 })
  dishCategoryList.value = res.data.data
}
//查询某各分类下面的菜品列表
//获取全部菜品列表
const dishList = ref([])
const getDishListNoPage = async () => {
  // 获取所有分类下的全部菜品
  const res = await reqDishListNoPage()
  dishList.value = res.data.data
}

const dishInCategoryList = ref([])
//只显示启售状态的候选菜品
const handleGetCategoryDishes = async (categoryId) => {
  // console.log(categoryId)

  // 从全部菜品中，筛选出当前分类的菜品
  dishInCategoryList.value = dishList.value.filter((dish) => {
    return dish.categoryId == categoryId
  })
  // 如果当前展示的候选菜品中，有的已经在【已选列表】中，则打钩
  // 给el-table设置row-key="id"属性，绑定唯一属性id,以及在勾选框一栏添加:reserve-selection="true"属性。
  dishCheckedList.value.forEach((row) => {
    console.log(row)
    dishListTableRef.value.toggleRowSelection(row, true)
  })
}
// 复选框绑定的id，用于数据回显时，将是否选中的状态一并回显
const getRowKey = (row) => {
  return row.id
}

// 当用户从候选列表中选择的菜品发生变化了，触发这个事件
const onSelectOneDish = (rows, row) => {
  // rows是已选择的所有行，row是当前行
  console.log(row)
  // 获取当前row 是被选中，还是取消选中
  let rowSelected = rows.length && rows.indexOf(row) !== -1
  //从当前选择的列表currentCheckedList中，找到新增的，添加到dishCheckedList中；如果有删除的，需要删掉
  // dishList.value.forEach((dish) => {})
  if (rowSelected) {
    //选中就添加
    dishCheckedList.value.push(row)
  } else {
    // 取消选中就删除
    dishCheckedList.value = dishCheckedList.value.filter((dish) => {
      return dish.id !== row.id
    })
  }
}

//全选当前类别下面的菜品，添加到{已选列表}中
const onSelectAllDish = (currentList) => {
  //添加菜品时，重复的要去掉
  console.log(currentList)
  //1.先将两个数组合并,可能会有重复的
  dishCheckedList.value = dishCheckedList.value.concat(currentList)
  //2.去掉重复的菜品
  dishCheckedList.value = removeDuplicates(dishCheckedList.value)
}

//数组去重复
function removeDuplicates(arr) {
  let obj = {} //obj用来记录该项重复出现了几次
  let brr = [] //brr是去重后的数组
  // item的id重复，就算重复了
  arr.forEach((item) => {
    if (obj[item.id] == undefined) {
      obj[item.id] = 1
      brr.push(item)
    } else {
      obj[item.id] += 1
    }
  })
  return brr
}

//从已选列表中，移除已经选择的菜品
const removeDish = (id) => {
  // console.log(id)
  dishCheckedList.value = dishCheckedList.value.filter((item) => {
    return item.id != id
  })
}

//添加菜品到套餐
const emit = defineEmits(['dishAddSuccess'])
const onDishAddSuccess = () => {
  if (dishCheckedList.value.length === 0) {
    ElMessage.error('还未选择菜品！')
    return
  }

  //每个菜品默认是1份
  dishCheckedList.value.forEach((dish) => {
    dish.copies = 1
  })
  //传递dishCheckedList给父组件
  emit('dishAddSuccess', dishCheckedList.value)
  //关闭窗口
  dialogFormVisible.value = false
}
//取消添加菜品到套餐
const onDishAddCancel = () => {
  //关闭窗口
  dialogFormVisible.value = false
}

//onMounted
onMounted(() => {
  getDishCategoryList()
  getDishListNoPage()
})
</script>

<style scoped>
.dish-checked {
  padding: 0px 10px;
  border-left: 1px solid #dcdfe6;
}
.dish-checked .checked-title {
  text-align: center;
  font-size: 14px;
  font-weight: 700;
  color: #909399;
}
.checked-items {
  padding: 10px;
}

.checked-items .item {
  box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
  display: flex;
  justify-content: space-between;
  text-align: center;
  font-size: 14px;
  padding: 5px 10px;
  margin-bottom: 10px;
  border-radius: 5px;
  color: #818693;
  background-color: #fae17c;
}

.checked-items .item .dish-name {
  flex: 1;
}

.checked-items .item .price {
  display: inline-block;
  flex: 1;
}
.checked-items .item .del {
  cursor: pointer;
}
.checked-items .item .del img {
  position: relative;
  top: 3px;
  width: 20px;
}
</style>
